package com.jy.admin.jobs;

import com.aliyun.oss.model.OSSObject;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.crawler.BrowserManager;
import com.jy.admin.crawler.DriverId;
import com.jy.admin.db.dao.OpdCsvExpandDao;
import com.jy.admin.db.dao.OpdUploadRecordDao;
import com.jy.admin.db.entity.OpdUploadRecordEntity;
import com.jy.admin.enums.OpdUploadStatusEnum;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.TextDetection;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.coordinates.WebDriverCoordsProvider;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/11/27
 * Time: 12:12 上午
 * <p>
 * csv展开任务
 */
@Service
public class ExcelExpandJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExpandJob.class);

    @Autowired
    private OpdUploadRecordDao opdUploadRecordDao;

    @Autowired
    private OpdCsvExpandDao opdCsvExpandDao;

    @Autowired
    private OSSService ossService;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    private WebDriver driver;


//    @Scheduled(fixedDelay = 1000L * 30)
    public void run() {

        LOGGER.info("== start csv expand job ==");
        Page page = new Page();
        page.setPageSize(100);
        List<OpdUploadRecordEntity> listByStatus = opdUploadRecordDao.getListByStatus(OpdUploadStatusEnum.WAITING.getStatus(), page);
        if (CollectionUtils.isEmpty(listByStatus)) {
            LOGGER.info("== start csv expand job , size is 0 ==");
            return;
        }

        LOGGER.info("== start csv expand job == size:{}", listByStatus.size());
        listByStatus.forEach(record -> {
            String ossUrlFull = record.getOssUrl();
            String[] coms = ossUrlFull.split("excel");
            String ossPath = coms[1];
            if (ossPath.startsWith("\\")) {
                ossPath = ossPath.substring(1, ossPath.length());
            }
            OSSObject ossObject = ossService.getObject(apolloConfigUtil.getBucketName(), "excel" + ossPath);
            List<String> mobiles = getCsvData(ossObject);
            try {
                record.setStatus(OpdUploadStatusEnum.EXPANDING.getStatus());
                opdUploadRecordDao.updateByPrimaryKey(record);

                int totalMobilesNum = storeMobile(record.getMerchantCode(), record.getDataNo(), mobiles);

                record.setStatus(OpdUploadStatusEnum.FINISHED.getStatus())
                        .setTotalCnt(totalMobilesNum);
                opdUploadRecordDao.updateByPrimaryKey(record);
            } catch (Exception e) {
                LOGGER.error("== 保存数据错误 ==", e);
            }
        });

    }

    public List<String> getCsvData(OSSObject ossObject) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent(), "utf-8"))) {

            // 读取csv文件
            CSVParser parser = getCsvRecords(reader);
            //遍历每一行数据
            List<CSVRecord> csvRecords = parser.getRecords();
            //第一行数据是字段名称   跳过
            if (CollectionUtils.isEmpty(csvRecords)) {
                return null;
            }
            List<String> mobiles = new ArrayList<>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);

                try {
                    String mobile = record.get(0).trim();
                    mobile = mobile.substring(mobile.length() - 10);
                    mobiles.add(mobile);
                    LOGGER.info("====,mobile:{}", record.get(0).trim());
                } catch (Exception e) {
                    LOGGER.error("== 解析csv mobile错误 ==", e);
                }
            }

            return mobiles;
        } catch (Exception e) {
            LOGGER.error("== 解析csv mobile错误22 ==", e);
        }

        return null;
    }

    public int storeMobile(String merchantCode, String dataNo, List<String> mobiles) {

        if (CollectionUtils.isEmpty(mobiles)) {
            return 0;
        }

        int cnt = 0;
        int totalCnt = 0;
        List<String> storeMobilesEach = new ArrayList<>();

        for (String mobile : mobiles) {
            if (StringUtils.isEmpty(mobile.trim())) {
                continue;
            }
            cnt++;
            totalCnt++;
            storeMobilesEach.add(mobile);
            if (cnt > 500) {
                opdCsvExpandDao.saveBatchMobile(merchantCode, dataNo, storeMobilesEach);
                cnt = 0;
                storeMobilesEach.clear();
            }
        }

        //保存最后一次
        opdCsvExpandDao.saveBatchMobile(merchantCode, dataNo, storeMobilesEach);
        return totalCnt;
    }

    private CSVParser getCsvRecords(BufferedReader reader) throws IOException {

        return CSVFormat.DEFAULT.withHeader("mobile").parse(reader);
    }

}
